import * as PIXI from 'pixi.js';

const posNames = ['tl', 't', 'tr', 'r', 'br', 'b', 'bl', 'l'];

const CtrlPointPosOf = R.prop(R.__, {
  tl: size => ({ x: 0, y: 0 }),
  t: size => ({ x: size.width * .5, y: 0 }),
  tr: size => ({ x: size.width, y: 0 }),
  r: size => ({ x: size.width, y: size.height * .5 }),
  br: size => ({ x: size.width, y: size.height }),
  b: size => ({ x: size.width * .5, y: size.height }),
  bl: size => ({ x: 0, y: size.height }),
  l: size => ({ x: 0, y: size.height * .5 }),
});


export const ToChange = R.prop(R.__, {
  tl: ['x', 'y'], tr: ['x', 'y'], br: ['x', 'y'], bl: ['x', 'y'],
  l: ['x'], r: ['x'],
  t: ['y'], b: ['y'],
});

const Cursor = R.prop(R.__, {
  tl: 'nwse-resize', br: 'nwse-resize',
  tr: 'nesw-resize', bl: 'nesw-resize',
  l: 'ew-resize', r: 'ew-resize',
  t: 'ns-resize', b: 'ns-resize',
});

export const siblingOf = ctrlPoint => name => ctrlPoint.parent.ctrlPointMap[name];

/** DisplayObject 的坐标转成类似 event.global */
export const toGlobal = o => o.toGlobal(o.pivot);

// - [ ] 避免滥用 useWith
/** 用单方向控制点 name 找对应的两方向控制点 name */
export const getActivePosName = R.ifElse(
  R.propEq(2, 'length'),
  R.identity,
  R.useWith( R.find(R.__, ['tl', 'br']), [R.includes] )
);

export const getOppoPointName = R.prop(R.__, { tl: 'br', br: 'tl', tr: 'bl', bl: 'tr' });

function CtrlPoint(posName) {
  const o = new PIXI.Graphics();

  o.name = posName;
  o.cursor = Cursor(o.name);
  o.visible = false;

  return o;
}

export function addCtrlPoint(f) {
  return function({ xs, rectBox }) {
    const dataItem = R.find(R.propEq(rectBox.id, 'id'), xs.value);

    Object.assign(rectBox, {
      ctrlPointMap: R.compose( R.fromPairs, R.map(posName => [posName, CtrlPoint(posName)]) )(posNames),
    });
  
    // 使控制点可拖拽和拖拽操作数据等写进函数定制
    Object
    .values(rectBox.ctrlPointMap)
    .forEach(ctrlPoint => {
      rectBox.addChild(ctrlPoint);
      Object.assign(ctrlPoint, CtrlPointPosOf(ctrlPoint.name)(dataItem));
      f({ xs, ctrlPoint });
      ctrlPoint.eventMode = rectBox.eventMode;
    });
  
    return { xs, rectBox };
  }
}

export function drawCtrlPointMap(Params) {
  return function({ dataItem, rectBox }) {
    // 不管画不画，坐标还是要更新的
    const r = Params();
    Object
    .values(rectBox.ctrlPointMap)
    .forEach(ctrlPoint => {
      Object.assign(ctrlPoint, CtrlPointPosOf(ctrlPoint.name)(dataItem));
      dataItem.visible && draw(ctrlPoint);

      function draw(ctrlPoint) {
        ctrlPoint.clear();
        ctrlPoint.beginFill(dataItem.color);
        ctrlPoint.drawCircle(0, 0, r);
        ctrlPoint.endFill();
      }
    });

    return { dataItem, rectBox };
  }
}

export const setCtrlPointVisible = R.curry((visible, rectBox) => {
  Object
  .values(rectBox.ctrlPointMap)
  .forEach(ctrlPoint => ctrlPoint.visible = visible);
});
